"""管理默认环境设置 Template Router"""
import re
import socket
from typing import List

from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import RedirectResponse
from sqlalchemy import select

from core.database import db_session
from core.exception import AlertException
from core.formclass import ConfigForm
from core.models import Config
from core.template import AdminTemplates
from lib.common import get_client_ip, get_host_public_ip
from lib.dependency.dependencies import validate_super_admin, validate_token
from lib.template_functions import (
    get_editor_select, get_member_level_select, get_skin_select,
    get_member_id_select
)

router = APIRouter()
templates = AdminTemplates()
# Python函数和变量 jinja2 注册以供使用
templates.env.globals["get_member_id_select"] = get_member_id_select
templates.env.globals["get_skin_select"] = get_skin_select
templates.env.globals["get_editor_select"] = get_editor_select
templates.env.globals["get_member_level_select"] = get_member_level_select

CONFIG_MENU_KEY = "100100"


@router.get("/config_form", dependencies=[Depends(validate_super_admin)])
async def config_form(request: Request):
    """
    基本环境设置窗体
    """
    request.session["menu_key"] = CONFIG_MENU_KEY

    host_name = socket.gethostname()
    host_ip = socket.gethostbyname(host_name)
    host_public_ip = await get_host_public_ip()
    client_ip = get_client_ip(request)

    context = {
        "request": request,
        "config": request.state.config,
        "host_name": host_name,
        "host_ip": host_ip,
        "host_public_ip": host_public_ip,
        "client_ip": client_ip,
    }
    return templates.TemplateResponse("config_form.html", context)


@router.post("/config_form_update",
             dependencies=[Depends(validate_token),
                           Depends(validate_super_admin)])
async def config_form_update(
    request: Request,
    db: db_session,
    social_list: List[str] = Form(None, alias="cf_social_servicelist[]"),
    form_data: ConfigForm = Depends(),
):
    """
    保存默认环境设置
    """
    # 阻塞 IP 当前对列表的访问权限 IP 如果有，连接将是不可能的，所以不要保存.
    if form_data.cf_intercept_ip:
        client_ip = get_client_ip(request)
        ip_patterns = form_data.cf_intercept_ip.split("\n")
        for pattern in ip_patterns:
            if not pattern.strip():
                continue
            pattern = pattern.replace(".", r"\.")
            pattern = pattern.replace("+", r"[0-9\.]+")
            if re.match(fr"^{pattern}$", client_ip):
                raise AlertException("当前访问 IP : " + client_ip + " 可以被阻止，所以其他 IP请输入.")

    # 检查您的身份验证设置
    if (form_data.cf_cert_use
        and not any([form_data.cf_cert_ipin, form_data.cf_cert_hp, form_data.cf_cert_simple])):
        raise AlertException("Ipin为您自己的确认, 检查您的手机, KG请为Innis选择一个或多个easy authentication services.")

    if not form_data.cf_cert_use:
        form_data.cf_cert_ipin = form_data.cf_cert_hp = form_data.cf_cert_simple = ""

    # 社交登录设置
    # 将数据转换为数组到字符串. 是) "naver,kakao,facebook,google,twitter,payco"
    form_data.cf_social_servicelist = ','.join(social_list) if social_list else ""

    # 反映表单数据后 commit
    config = db.scalars(select(Config)).one()
    for field, value in form_data.__dict__.items():
        setattr(config, field, value)
    db.commit()

    return RedirectResponse("/admin/config_form", status_code=303)
